/*
 * Author: yezi
 * E-mail: okye328@gmail.com
 * Create time: Dec 21, 2012 3:53:54 PM
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

package com.kanbox.linux.token.ui;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kanbox.linux.GlobalConf;
import com.kanbox.linux.token.Authenticator;
import com.kanbox.linux.token.URLExtractor;

public class AuthenticationUI {

	private static Logger logger = LoggerFactory
			.getLogger(AuthenticationUI.class);

	protected Shell shell;

	private Browser browser;

	private Authenticator authenticator;

	public AuthenticationUI(Authenticator authenticator) {
		createContents();
		this.authenticator = authenticator;
	}

	/**
	 * Launch the application.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			AuthenticationUI window = new AuthenticationUI(null);
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();

		shell.setLocation(new Point((display.getClientArea().width - 350) / 2,
				(display.getClientArea().height - 430) / 2));
		shell.setSize(350, 430);

		shell.open();
		shell.layout();

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		display.dispose();
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();

		shell.setText("请登陆酷盘并授权");
		shell.setLayout(new FillLayout(SWT.HORIZONTAL));

		initBrowser();
	}

	public void setURL(String url) {
		browser.setUrl(url);

	}

	private void initBrowser() {

		browser = new Browser(shell, SWT.NONE);
		browser.setTouchEnabled(true);

		browser.addLocationListener(new LocationListener() {

			@Override
			public void changing(LocationEvent event) {
				String location = event.location;
				logger.debug("Get redirect:" + location);
				if (location.startsWith(GlobalConf.NATIVE_REDIRECT_URL)) {
					URLExtractor ue = new URLExtractor(location);
					String code = ue.getString("code");
					if (code == null) {
						String error = ue.getString("error");
						if (error != null) {
							showDialog(error);
						} else {
							showDialog("未知错误");
						}
					} else {
						authenticator.setAuthCode(code);
						browser.stop();
						browser.dispose();
						shell.dispose();
					}
				}
			}

			@Override
			public void changed(LocationEvent event) {
				// Do nothing now

			}
		});
	}

	public void showDialog(String error) {
		MessageBox mb = new MessageBox(shell, SWT.ERROR);
		mb.setText("获取AuthCode出错");
		mb.setMessage(error + "，请联系作者okye328@gmail.com");
		mb.open();
	}
}
